#!/bin/sh

if [ $# -ge 1 ]; then
	files="$*"
else
	files=$(grep -r -l /bin/bash bin monitors setup tests)
fi

sed -r -i \
	-e 's,^#!/bin/bash,#!/bin/sh,' \
	$files


sed -r -i \
	-e 's/^(\s*)source /\1. /' \
	-e 's/^(\s*)function /\1/' \
	-e 's/([a-zA-Z_]+)\+="/\1="${\1}/' \
	-e 's/([a-zA-Z_]+)\+=([^'\'']+)$/\1="${\1}\2"/' \
	-e 's/([a-zA-Z_]+)\+=/\1="$\1"/' \
	-e 's/ &>(.+)([&|])/ >\1 2>\&1\2/' \
	-e 's/ &>(.+)$/ >\1 2>\&1/' \
	$files


sed -r -i \
	-e 's/\(\(\s+([^ ]+)\s*\)\)/[ -n "$\1" -a "$\1" != 0 ]/' \
	-e 's/\(\(\s+([^ ]+)\s*=\s*(.+)\s*\)\)/\1=$(( \2 ))/' \
	-e 's/\(\(\s+([a-zA-Z_]+) > ([a-zA-Z_]+)\s*\)\)/[ "$\1" -gt "$\2" ]/' \
	-e 's/\(\(\s+([a-zA-Z_]+) < ([a-zA-Z_]+)\s*\)\)/[ "$\1" -lt "$\2" ]/' \
	-e 's/\(\(\s+([a-zA-Z_]+) >= ([a-zA-Z_]+)\s*\)\)/[ "$\1" -ge "$\2" ]/' \
	-e 's/\(\(\s+([a-zA-Z_]+) <= ([a-zA-Z_]+)\s*\)\)/[ "$\1" -le "$\2" ]/' \
	-e 's/\(\(\s+([a-zA-Z_]+) > (.+)\s*\)\)/[ "$\1" -gt \2 ]/' \
	-e 's/\(\(\s+([a-zA-Z_]+) < (.+)\s*\)\)/[ "$\1" -lt \2 ]/' \
	-e 's/\(\(\s+([a-zA-Z_]+) >= (.+)\s*\)\)/[ "$\1" -ge \2 ]/' \
	-e 's/\(\(\s+([a-zA-Z_]+) <= (.+)\s*\)\)/[ "$\1" -le \2 ]/' \
	-e 's/\(\(\s+(.+) > ([a-zA-Z_]+)\s*\)\)/[ \1 -gt "$\2" ]/' \
	-e 's/\(\(\s+(.+) < ([a-zA-Z_]+)\s*\)\)/[ \1 -lt "$\2" ]/' \
	-e 's/\(\(\s+(.+) >= ([a-zA-Z_]+)\s*\)\)/[ \1 -ge "$\2" ]/' \
	-e 's/\(\(\s+(.+) <= ([a-zA-Z_]+)\s*\)\)/[ \1 -le "$\2" ]/' \
	$files


sed -r -i \
	-e 's/\$\(<\s*/$(cat /' \
	$files


sed -r -i \
	-e 's/\[\[ \$([^ ]+) =\~ '\''([^ ]+)'\''\s+\]\]/[ "${\1#*\2}" != "$\1" ]/g' \
	-e 's/\[\[ \$([^ ]+) =\~ ([^ ]+)\s+\]\]/[ "${\1#*\2}" != "$\1" ]/g' \
	$files


sed -r -i \
	-e 's/\[\[\s+([^ ]+) \&\& ([^ ]+)\s+\]\]/[ \1 -a \2 ]/g' \
	-e 's/\[\[\s+([^ ]+) \|\| ([^ ]+)\s+\]\]/[ \1 -o \2 ]/g' \
	-e 's/\[\[\s+([^ ]+) \= ([^ ]+)\s+\]\]/[ \1 = \2 ]/g' \
	-e 's/\[\[\s+([^ ]+) \=\= ([^ ]+)\s+\]\]/[ \1 = \2 ]/g' \
	-e 's/\[\[\s+([^ ]+) \!\= ([^ ]+)\s+\]\]/[ \1 != \2 ]/g' \
	-e 's/\[\[\s+([^ ]+) (-[a-zA-Z]+) ([^ ]+)\s+\]\]/[ \1 \2 \3 ]/g' \
	-e 's/\[\[\s+(-[a-zA-Z]) "([^ ]+)"\s+\]\]/[ \1 "\2" ]/g' \
	-e 's/\[\[\s+(-[a-zA-Z]) ([^ ]+)\s+\]\]/[ \1 "\2" ]/g' \
	-e 's/\[\[\s+"([^ ]+)"\s+\]\]/[ -n "\1" ]/g' \
	-e 's/\[\[\s+([^ ]+)\s+\]\]/[ -n "\1" ]/g' \
	-e 's/\[\[\s+\! "([^ ]+)"\s+\]\]/[ -z "\1" ]/g' \
	-e 's/\[\[\s+\! ([^ ]+)\s+\]\]/[ -z "\1" ]/g' \
	$files

checkbashisms $files
echo "$files" | xargs -n1 bash -n
